#include "board.h"
#include "raylib.h"
#include <iostream>
#include <memory>
#include <cmath>

// Board实现
Board::Board(float x, float y, const GameConfig& gameConfig) : 
    position{x, y}, config(gameConfig), active(true), isCracked(false), crackTimer(0.0f), type("NormalBoard") {
    color = BLUE; // 默认蓝色
}

Rectangle Board::GetRect() const {
    return Rectangle{position.x, position.y, config.boardWidth, config.boardHeight};
}

void Board::Update() {
    // 所有板子都向上移动
    position.y -= config.boardMoveSpeed;
    
    // 如果板子已破裂，则处理闪烁效果
    if (isCracked) {
        crackTimer -= GetFrameTime();
        if (crackTimer <= 0) {
            active = false; // 时间到了之后才真正消失
        }
    }

    // 如果板子移出屏幕顶端，则将其设为非活跃等待重新生成
    if (position.y < -config.boardHeight) {
        active = false;
    }
}

void Board::Draw() {
    if (active) {
        if (isCracked) {
            // 破裂的板子以不同方式显示
            DrawRectangle(position.x, position.y, config.boardWidth, config.boardHeight, Fade(color, 0.3f));
            
            // 实现闪烁效果
            float alpha = 0.5f + 0.5f * sinf(GetTime() * 10.0f); // 基于时间的闪烁
            
            // 绘制闪电状裂缝效果
            // 主要的垂直裂缝
            DrawRectangle(position.x + config.boardWidth/2 - 2, position.y, 4, config.boardHeight, Fade(YELLOW, alpha));
            
            // 添加一些分支闪电效果
            DrawRectangle(position.x + config.boardWidth/2 - 8, position.y + config.boardHeight/4, 3, config.boardHeight/3, Fade(YELLOW, alpha));
            DrawRectangle(position.x + config.boardWidth/2 + 5, position.y + config.boardHeight/3, 3, config.boardHeight/4, Fade(YELLOW, alpha));
            DrawRectangle(position.x + config.boardWidth/2 - 3, position.y + 2*config.boardHeight/3, 6, 3, Fade(YELLOW, alpha));
        } else {
            // 绘制板子
            DrawRectangle(position.x, position.y, config.boardWidth, config.boardHeight, color);
            
            // 如果是可破坏板子，添加一个X标记使其更加明显
            if (type == "BreakingBoard") {
                DrawLine(position.x, position.y, position.x + config.boardWidth, position.y + config.boardHeight, WHITE);
                DrawLine(position.x + config.boardWidth, position.y, position.x, position.y + config.boardHeight, WHITE);
            }
        }
    }
}

bool Board::CheckCollision(Rectangle playerRect) {
    Rectangle boardRect = GetRect();
    return ::CheckCollisionRecs(playerRect, boardRect);
}

void Board::OnPlayerLand() {
    // 如果是可破坏板子，开始破裂过程
    if (type == "BreakingBoard" && !isCracked) {
        isCracked = true;
        crackTimer = 1.0f; // 1秒后消失
    }
}

void Board::Reset(float x, float y) {
    SetPosition(x, y);
    active = true;
    isCracked = false;
    crackTimer = 0.0f;
}

bool Board::IsBreakable() const {
    return type == "BreakingBoard";
}

void Board::SetType(const std::string& newType) {
    type = newType;
    if (type == "NormalBoard") {
        color = BLUE;
    } else if (type == "BreakingBoard") {
        color = RED;
    }
}
